package UDP_chat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Scanner;

public class ChatServerUDP {
	public static void main(String[] args) throws IOException{
		//0. tao cong lang nghe port 7777
		DatagramSocket serverSK=new DatagramSocket(7777);
		String chuoixuly;
		do{
			byte []buf=new byte[1024];
			DatagramPacket serverPK=new DatagramPacket(buf ,buf.length);
			//2.1 nhan yeu cau tu client
			serverSK.receive(serverPK);
			//xu ly chuoi
			chuoixuly=new String(serverPK.getData());
			System.out.println("Client: "+chuoixuly.trim());
			
			if (chuoixuly.trim().equalsIgnoreCase("exit"))
			{
				serverPK=new DatagramPacket("exit".getBytes(), "exit".getBytes().length, serverPK.getAddress(), serverPK.getPort());
				serverSK.send(serverPK);
				break;
			}
			//doc noi dung 
			Scanner input=new Scanner(System.in);
			System.out.println("Server: ");
			chuoixuly=input.nextLine();
			
			byte[] data=chuoixuly.getBytes();
			serverPK=new DatagramPacket(data, data.length, serverPK.getAddress(), serverPK.getPort());
			serverSK.send(serverPK);
			input.close();
		}
		while(!chuoixuly.trim().equalsIgnoreCase("exit"));
		serverSK.close();
		System.out.println("tu server");
	}
}
